package com.exam.system.utils;

import com.exam.system.entity.ExamUser;
import com.exam.system.redis.RedisUtils;
import com.exam.system.service.ExamUserService;
import com.exam.system.token.MyJsonWebToken;
import org.apache.catalina.Manager;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

/**
 * @ClassName MyRealm
 * @Description
 * @Author ckl
 * @DATE 2021/5/21 11:14
 * @versions 1.0
 */
@Configuration
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private ExamUserService examUserService;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 判断token的来源
     *
     * @param token 用户登陆传进来的token
     * @return 根据token的类型返回相应的布尔值
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof MyJsonWebToken;
    }

    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        String principal = principals.getPrimaryPrincipal().toString();
        return info;
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//        System.out.println("MyRealm.doGetAuthenticationInfo=" + token + "============");

        String myJWT = token.getCredentials().toString();

        String userName = JwtUtils.getUserName(myJWT);

        String redisToken = redisUtils.get("token" + userName).toString();

        return new SimpleAuthenticationInfo(myJWT, redisToken, this.getName());

    }
}
